package com.yejiali.backend.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yejiali.backend.common.annotaion.SystemLog;
import com.yejiali.backend.common.httpcode.HttpCodeEnum;
import com.yejiali.backend.entity.MedicalCase;
import com.yejiali.backend.entity.Patients;
import com.yejiali.backend.entity.dto.PatientsDTO;
import com.yejiali.backend.entity.vo.PatientInfoVo;
import com.yejiali.backend.entity.dto.PatientPageInfoDTO;
import com.yejiali.backend.exception.SystemException;
import com.yejiali.backend.mapper.PatientsMapper;
import com.yejiali.backend.response.Response;
import com.yejiali.backend.service.PatientsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * (Patients)表服务实现类
 *
 * @author yejiali
 * @since 2025-05-15 11:14:23
 */
@Service("patientsService")
public class PatientsServiceImpl extends ServiceImpl<PatientsMapper, Patients> implements PatientsService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /***
     * 按时间查询分页最近记录（用于初始化表格）
     * @param currentPage 当前页数
     * @param pageSize 每页记录数
     * @return 分页结果
     */
  @Override
  @SystemLog("获取初始化数据")
  public Response initData(int currentPage, int pageSize) {
      //按创建时间降序
      LambdaQueryWrapper<Patients> lambdaQueryWrapper=new LambdaQueryWrapper<>();
      lambdaQueryWrapper.orderByDesc(Patients::getCreatedTime);
      //分页查询
      Page<Patients> page=new Page<>(currentPage,pageSize);
      page(page,lambdaQueryWrapper);
      //查询结果
      List<Patients> records = page.getRecords();
      //获取总记录数
      long total = page.getTotal();
      //封装数据
      List<PatientInfoVo> patientInfoVos = BeanUtil.copyToList(records, PatientInfoVo.class);
      PatientPageInfoDTO patientPageInfoDTO = new PatientPageInfoDTO(total, patientInfoVos);
      return Response.success(patientPageInfoDTO);
  }

    /**
     * 由姓名查询
     * @param patientName
     * @return
     */
    @Override
    public Response queryByName(String patientName, int currentPage, int pageSize) {
        //按姓名查询
        LambdaQueryWrapper<Patients> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Patients::getName,patientName);
        //查询
        Page<Patients> page=new Page<>(currentPage,pageSize);
        page(page,lambdaQueryWrapper);
        List<Patients> patientsList = page.getRecords();
        //获取分页信息
        long total = page.getTotal();
        //封装
        List<PatientInfoVo> patientInfoVos = BeanUtil.copyToList(patientsList, PatientInfoVo.class);
        PatientPageInfoDTO patientPageInfoDTO = new PatientPageInfoDTO(total, patientInfoVos);
        return Response.success(patientPageInfoDTO);
    }

    /**
     * 由身份证查询
     * @param idCard
     * @return
     */
    @Override
    public Response queryByIdcard(String idCard) {
        //按身份证查询
        LambdaQueryWrapper<Patients> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Patients::getCardId,idCard);
        //查询 这里list形式返回
        List<Patients> patients = list(lambdaQueryWrapper);
        //判断
        if(patients.size()==0){
            return Response.success(patients);
        }
        //封装
        List<PatientInfoVo> patientInfoVos = BeanUtil.copyToList(patients, PatientInfoVo.class);
        // TODO 有点问题
        PatientPageInfoDTO patientPageInfoDTO = new PatientPageInfoDTO(patientInfoVos.size(), patientInfoVos);
        return Response.success(patientPageInfoDTO);
    }

    /**
     * 由id查询
     * @param patientid
     * @return
     */

    @Override
    public Response queryById(Long patientid) {
        //查询
        Patients patients = getById(patientid);
        //判断
        if(patients==null){
            return Response.error(HttpCodeEnum.PATIENT_NOT_FOUND.getCode(),"该患者不存在");
        }
        //封装
        PatientInfoVo patientInfoVo = BeanUtil.copyProperties(patients, PatientInfoVo.class);
        return Response.success(patientInfoVo);
    }

    /**
     * 新增病人档案
     * @param patientsDTO
     * @return
     */
    @Override
    public Response add(PatientsDTO patientsDTO) {
        //判断（由身份证号判断）
        LambdaQueryWrapper<Patients> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Patients::getCardId,patientsDTO.getCardId());
        Patients patients = getOne(lambdaQueryWrapper);
        if(patients!=null){
            return Response.error(HttpCodeEnum.PATIENT_EXIST.getCode(),"该患者已存在");
        }
        //封装
        Patients patients1 = BeanUtil.copyProperties(patientsDTO, Patients.class);
        //设置存档时间
        patients1.setCreatedTime(new Date());
        //插入
        try {
            save(patients1);
        }catch (Exception e) {
            throw new SystemException(HttpCodeEnum.PATIENT_ADD_ERROR);
        }
        return Response.success("添加成功");
    }

    /**
     * 由身份证删除
     * @param idCard
     * @return
     */

    @Override
    public Response deleteByIdCard(String idCard) {
        //判断
        LambdaQueryWrapper<Patients> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Patients::getCardId,idCard);
        Patients patients = getOne(lambdaQueryWrapper);
        if(patients==null){
            return Response.error(HttpCodeEnum.PATIENT_NOT_FOUND.getCode(),"该患者不存在");
        }
        //删除
        try {
            remove(lambdaQueryWrapper);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Response.success("删除成功");
    }

    /**
     * 删除
     * @param patientid
     * @return
     */

    @Override
    public Response deleteById(Long patientid) {
        //判断
        Patients patients = getById(patientid);
        if(patients==null){
            return Response.error(HttpCodeEnum.PATIENT_NOT_FOUND.getCode(),"该患者不存在");
        }
        //删除
        try {
            removeById(patientid);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Response.success("删除成功");
    }


    /**
     * 根据病人id获取病例
     * @param
     * @return
     */
    public Response getCasesByPatientId(Long patientId) {
        Query query = new Query(Criteria.where("patientId").is(patientId));
        List<MedicalCase> medicalCases = mongoTemplate.find(query, MedicalCase.class);
        //判断是否存在
        String data = "获取成功";
        if(medicalCases.size() == 0){
            data="暂无病例";
        }
        return Response.success(medicalCases,data);

    }


}


